package com.onetech.adrewards.free.fragments;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fedorvlasov.lazylist.ImageLoader;
import com.google.analytics.tracking.android.EasyTracker;
import com.onetech.adrewards.free.R;
import com.onetech.adrewards.free.models.CommonModel;
import com.onetech.adrewards.free.objects.InviteFriendDTO;
import com.todddavies.components.progressbar.ProgressWheel;

public class InviteFriendsFragment extends BaseFragment {
	protected View mBtnRetry=null;
	protected ProgressWheel mProgress=null;
	
	private View mMainView=null;
	//private TextView mHeader=null;
	private TextView mMessage1=null;
	private TextView mMessage2=null;
	private EditText mInviteMessage=null;
	private TextView mInviteNote=null;
	private View mCopyBtn=null;
	private View mCopyInviteCodeBtn=null;
	private View mInviteBtn=null;
	private InviteFriendDTO mInviteData=null;
	private ImageView mImageview=null;
	private LoadInviteDataTask mLoadInviteDataTask=null;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mView == null) {
			mView = inflater.inflate(R.layout.activity_invite_friend_layout, container,
					false);
			initView();
			initListener();			

		} else {
			((ViewGroup) mView.getParent()).removeView(mView);
		}
		return mView;
	}
	private void initView() {
		
	//	mHeader = (TextView)findViewById(R.id.header);
		mMessage1=(TextView)mView.findViewById(R.id.msg1);
		//mMessage2=(TextView)findViewById(R.id.msg2);
		mInviteMessage=(EditText)mView.findViewById(R.id.msg3);
		mInviteNote=(TextView)mView.findViewById(R.id.inviteNote);
		mImageview = (ImageView)mView.findViewById(R.id.imageView1);
		mCopyBtn=(LinearLayout)mView.findViewById(R.id.copyTextBtn);
		mCopyInviteCodeBtn=(LinearLayout)mView.findViewById(R.id.copyInviteCodeBtn);
		mInviteBtn=(LinearLayout)mView.findViewById(R.id.inviteBtn);
		
		initNotFoundAndLoadingView();
		mMainView=(LinearLayout)mView.findViewById(R.id.mainContainer);
		showMainView(false);
	}
	private void showMainView(boolean isShow){
		mMainView.setVisibility(isShow?View.VISIBLE:View.GONE);
	}
	private void initListener() {
		mCopyBtn.setOnClickListener(this);
		mCopyInviteCodeBtn.setOnClickListener(this);
		mInviteBtn.setOnClickListener(this);
		initRetryButtonListener();
	}
	
	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {	
		case R.id.copyTextBtn:
			if(copyToClipboard(getActivity(), mInviteData.invite_msg)){
				Toast.makeText(getActivity(), getString(R.string.copy_text_message_success), Toast.LENGTH_LONG).show();
			}else{
				Toast.makeText(getActivity(), getString(R.string.copy_text_message_failed), Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.copyInviteCodeBtn:
			if(copyToClipboard(getActivity(), mInviteData.invite_code)){
				Toast.makeText(getActivity(), getString(R.string.copy_text_message_success), Toast.LENGTH_LONG).show();
			}else{
				Toast.makeText(getActivity(), getString(R.string.copy_text_message_failed), Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.inviteBtn:
			sendInvite();
			break;
		case R.id.btnRetry:
			loadInviteData();
			break;
		default:
			super.onClick(v);
			return;
		}		
	}
	@Override
	public void onResume() {
		super.onResume();
		getBaseNewActivity().getUserInfo();
		if(mInviteData==null){
			loadInviteData();
		}
	}
	private void loadInviteData(){
		if(mInviteData==null){
			if(mLoadInviteDataTask==null || mLoadInviteDataTask.getStatus()==Status.FINISHED){
				mLoadInviteDataTask=new LoadInviteDataTask();
				mLoadInviteDataTask.execute();
			}
		}
	}
	
	private class LoadInviteDataTask extends AsyncTask<Void, Void, InviteFriendDTO>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();	
			showNotFoundOrLoadingView(false, true);
			showMainView(false);
		}
		@Override
		protected InviteFriendDTO doInBackground(Void... params) {
			try {
				return CommonModel.getInstance().getInviteFriendInfo();
			} catch (Exception e) {
 				return null;
			}			
		}
		@Override
		protected void onPostExecute(InviteFriendDTO result) {
			super.onPostExecute(result);
			try {
				if(result!=null){
					mInviteData=result;
					//mHeader.setText("å�‹é�”æ‹›å¾…ã�§ãƒ�ã‚¤ãƒ³ãƒˆGETï¼�ï¼�");
					mMessage1.setText(Html.fromHtml(mInviteData.msg1));
					//mMessage2.setText(Html.fromHtml(mInviteData.msg2));
					mInviteMessage.setText(Html.fromHtml(mInviteData.invite_msg));
					mInviteNote.setText(Html.fromHtml(mInviteData.invite_exp));
					ImageLoader.getInstance(null).DisplayImage(mInviteData.msg2, mImageview);
					
					showNotFoundOrLoadingView(false,false);
					showMainView(true);
				}else{
					showNotFoundOrLoadingView(true, false);
					showMainView(false);
				}
			} catch (Exception e) {
				showNotFoundOrLoadingView(true, false);
				showMainView(false);
			}
		}
	}
	@Override
	public void onStart() {
	    super.onStart();
	    try {
	    	EasyTracker.getInstance(getActivity()).activityStart(getActivity());  // Add this method.
		} catch (Exception e) {			
		}
	  }

	  @Override
	  public void onStop() {
	    super.onStop();
	    // The rest of your onStop() code.
	    try {
	    	EasyTracker.getInstance(getActivity()).activityStop(getActivity());  // Add this method.
		} catch (Exception e) {
		}
	  }
	  private void sendInvite(){
		  try {
			  if(mInviteData!=null){
				  Intent sendIntent = new Intent();
				  sendIntent.setAction(Intent.ACTION_SEND);
				  sendIntent.putExtra(Intent.EXTRA_TEXT, mInviteData.invite_msg);
				  sendIntent.setType("text/plain");
				  startActivityForResult(Intent.createChooser(sendIntent, getResources().getText(R.string.invite_friend_message_title)),0);
			  }
		} catch (Exception e) {
			return;
		}
	  }

	  @SuppressLint("NewApi")
	  @SuppressWarnings("deprecation")
	    public boolean copyToClipboard(Context context, String text) {
	        try {
	            int sdk = android.os.Build.VERSION.SDK_INT;
	            if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
	                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
	                        .getSystemService(context.CLIPBOARD_SERVICE);
	                clipboard.setText(text);
	            } else {
	                android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
	                        .getSystemService(context.CLIPBOARD_SERVICE);
	                android.content.ClipData clip = android.content.ClipData
	                        .newPlainText(
	                                context.getResources().getString(
	                                        R.string.invite_friend_message_title), text);
	                clipboard.setPrimaryClip(clip);
	            }
	            return true;
	        } catch (Exception e) {
	            return false;
	        }
	    }
}
